<?php
namespace app\admin\controller;
use think\Controller;
class Resource extends Controller
{
    public function index()
    {
    	$keyword = trim(input('get.keyword'));
    	if ($keyword == '' || $keyword == false){
    		$resource_list = db('resource')->field(['id','resource','path'])->paginate(10);
    	}else {
    		$resource_list = db('resource')->field(['id','resource','path'])->where('resource','like','%'.$keyword.'%')->paginate(10);
    		
    	}
        $page = $resource_list->render();
        $this->assign('resource_list',$resource_list);
        $this->assign('page',$page);
        return $this->fetch('index');
    }
    
    public function upload_file()
    {
        $result = array('err' => '1','content' => '');
        $resource_id = input('get.resource_id');
        $resourse_name = input('get.resource_name');
        $resourse_name = urldecode($resourse_name);
        $resource_id = urldecode($resource_id);
        $files = request()->file('resource_file');
        $file_name = $files->getInfo();
        $file_name = $file_name['name'];
        $file_name = iconv('utf-8','gb2312',$file_name);
        $info = $files->move(ROOT_PATH.'Uploads'.DS.'resource',$file_name);
        if ($info->getError()){
            $result['content'] = '上传失败';
            return json_encode($result,true);
        }
        $resourse_model = model('Resource');
        $resource_info = [
            'resource' => $resourse_name,
            'path' => iconv('gb2312','utf-8', $info->getSaveName()),
        ];
        if ($resource_id != ''){
            $resource_info['id'] = $resource_id;
        }
        $save_resource = $resourse_model->SaveResource($resource_info);
        if ($save_resource == false){
            $result['content'] = '保存失败！';
            return json_encode($result,true);
        }
        $result['err'] = '0';
        $result['content'] = '上传成功！';
        return json_encode($result,true);
    }
    public function edit_resource()
    {
        $resouce_id = input('get.resource_id');
        $resouce = db('resource')->field(['id','resource','path'])->where('id',$resouce_id)->find();
        $this->assign('resource',$resouce);
        return $this->fetch('edit');
    }
    
    public function del_resource()
    {
    	$result = array('err'=>'1','content' => '');
    	$resource_id = input('post.id');
    	$resource_path = db('resource')->where('id',$resource_id)->value('path');
    	$file_path = iconv('utf-8', 'gb2312', ROOT_PATH.'Uploads/resource/'.$resource_path);
    		
    	if (file_exists($file_path)){
    		unlink($file_path);
    	}
    	$del_resource = db('resource')->where('id',$resource_id)->delete();
    	if ($del_resource == false){
    		$result['content'] = '删除失败！'.$resource_id;
    		return $result;
    	}
    	$result['err'] = '0';
    	$result['content'] = '删除成功！';
    	return $result;
    	
    }
}
